/** * 公共组件->文件上传 */
<template>
  <div class="upload-file">
    <Upload
      ref="upload"
      :format="fileType"
      :accept="fileType.map(v => {return '.' + v}).join(',')"
      :show-upload-list="false"
      :on-success="handleUploadSuccess"
      :headers="headers"
      :on-format-error="handleUploadError"
      :on-exceeded-size="handleExceed"
      :before-upload="handleBeforeUpload"
      :multiple="limit > 1 ? true : false"
      :disabled="disabled"
      :action="uploadFileUrl"
    >
      <!-- 上传按钮 -->
      <Button type="primary" :class="{disNone: this.fileList.length >= this.limit}">选取文件</Button>
      <!-- 上传提示 -->
      <div class="upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
        的文件
      </div>
    </Upload>

    <!-- 文件列表 -->
    <ul class="upload-file-list">
      <li :key="file.id" class="upload-list__item upload-list__item-content" v-for="(file, index) in fileList">
        <a :href="fileBase + file.resUrl" target="_blank" class="file-name">
          <Icon type="ios-document" size="14" color="#606266"/>
          {{ file.resUrl }}
        </a>
        <div class="upload-list__item-content-action">
          <a @click="handleDelete(index)" class="delete">删除</a>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import {base} from "@/libs/axios";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["jpg", "jpeg", "png", "doc", "docx", "xls", "xlsx", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileBase: this.$config.fileUrl(),
      uploadFileUrl: base + this.$config.uploadUrl, // 上传的图片服务器地址
      headers: {
        token: JSON.parse(window.localStorage.getItem("myData")).token,
      },
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = {id: item, resUrl: item};
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$Notice.warning({
            title: '文件格式不正确',
            desc: `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`,
          })
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$Notice.warning({
            title: "上传失败",
            desc: `上传文件大小不能超过 ${this.fileSize} MB!`,
          });
          return false;
        }
      }
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$Notice.warning({
        title: `上传文件数量不能超过 ${this.limit} 个!`,
      })
    },
    // 上传失败
    handleUploadError(err) {
      this.$Notice.error({
        title: "上传失败, 请重试",
      });
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 20000) {
        this.fileList.push({id: res.data.id, resUrl: res.data.resUrl});
        this.$emit("input", this.fileList);
      } else {
        this.$Message.error(res.message);
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
    },
  },
};
</script>

<style scoped lang="less">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .upload-list__item:first-child {
  margin-top: 5px;
}

.upload-file-list .upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.file-name {
  font-size: 14px;
  color: #606266;
  margin-left: 10px;
  max-width: 80%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete {
  color: #F56C6C;
  margin-right: 10px;
  vertical-align: middle;
}

.upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
</style>
